<template>
	<view>
		<u-picker :show="showCateId" :columns="cateList" @cancel="showCateId = false" keyName='cateName'
			@confirm='bindPickerChange'></u-picker>
		<view style="background-color: #fff; padding: 0 20rpx;">



			<view class="remark" v-if="form.remark">
				<u-alert type="error" :show-icon="true" :title="'拒绝原因 :'+form.remark"></u-alert>
			</view>
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth='100'>
				<u-form-item label="店铺名称" prop="name" borderBottom>
					<u--input v-model="form.name" border="none" @blur="cacheAuthStore()"
						placeholder="请输入店铺名称"></u--input>
				</u-form-item>
				<u-form-item label="经营类型" prop="cateId" borderBottom @click="showCateId = true">
					<u--input v-model="cateName" disabled disabledColor="#ffffff" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<!-- <u-form-item label="地区" prop="province" borderBottom>

					<CitySelect ref="cityselect" :defaultValue="addressText" @callback="result" :items="district">
					</CitySelect>

					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item> -->
				<u-form-item label="联系方式" prop="phone" borderBottom>
					<u--input v-model="form.phone" border="none" @blur="cacheAuthStore()"
						placeholder="请输入联系方式"></u--input>
				</u-form-item>
				<!-- <u-form-item label="商家简介" prop="introduction" borderBottom>
					<u--input v-model="form.introduction" border="none" @blur="cacheAuthStore()"
						placeholder="请输入商家简介"></u--input>
				</u-form-item> -->
				<u-form-item label="详细地址" prop="detailedAddress" borderBottom @click.stop="toLoca()">
					<!-- <u--input v-model="form.detailedAddress" border="none" placeholder="请输入详细地址"></u--input>
					<u-icon name="map" slot="right" @click.stop="toLoca()"></u-icon> -->

					<u--input v-model="form.detailedAddress" border="none" @blur="cacheAuthStore()"
						placeholder="请输入详细地址" suffixIcon="map-fill" suffixIconStyle="color: #909399"
						disabled></u--input>
				</u-form-item>
				<u-form-item label="设置营业时间" prop="_dayTime" borderBottom
					@click="goTimePeriod(`/storeManagementPack/pages/timePeriod/index`)">
					<u--input v-model="form._dayTime " disabled border="none" placeholder="请设置营业时间"></u--input>
					<!-- {{form.dayTime ? '已配置' : '请设置'}} -->
				</u-form-item>
				<!-- <u-form-item label="营业结束时间" prop="dayTime_end" borderBottom @click="SelectTime(`dayTime_end`)">
					<u--input v-model="form.dayTime_end" disabled border="none" placeholder="请选择营业结束时间"></u--input>
				</u-form-item> -->

				<u-form-item label="核销开始时间" prop="validTime_start" borderBottom @click="SelectTime(`validTime_start`)">
					<u-input v-model="form.validTime_start" disabled border="none" placeholder="请选择核销开始时间">
						<!-- 	<template slot="suffix">
							<u-button
								@tap.stop="syncDayTime"
								text="同步营业时间"
								type="success"
								size="mini"
							></u-button>
						</template> -->
					</u-input>
				</u-form-item>
				<u-form-item label="核销结束时间" prop="validTime_end" borderBottom @click="SelectTime(`validTime_end`)">
					<u--input v-model="form.validTime_end" disabled border="none" placeholder="请输入核销结束时间"></u--input>
				</u-form-item>
				<u-form-item prop="businessLicense" label="上传营业执照" v-if="userInfo.roleLevel == 2 && userInfo.merchantType == 1">
					<u-upload accept="image" @afterRead="afterRead(1,$event)"
						@delete="(event, type) => deletePic(event, 1)" multiple :maxCount="1" width="210rpx"
						height="210rpx" :fileList="businessLicense" :sizeType="['compressed']"></u-upload>
				</u-form-item>
				<u-form-item prop="image" label="上传门店logo">
					<u-upload accept="image" @afterRead="afterRead(2,$event)"
						@delete="(event, type) => deletePic(event, 2)" multiple :maxCount="1" width="210rpx"
						height="210rpx" :fileList="image" :sizeType="['compressed']"></u-upload>
				</u-form-item>
				<u-form-item prop="carouselMap" label="商家轮播图">
					<u-upload accept="image" @afterRead="afterRead(3,$event)"
						@delete="(event, type) => deletePic(event, 3)" multiple :maxCount="4" width="210rpx"
						height="210rpx" :fileList="carouselMap" :sizeType="['compressed']"></u-upload>
				</u-form-item>
				<u-form-item label="其他资格证明"  v-if="userInfo.roleLevel == 2 && userInfo.merchantType == 1" >
					<u-upload accept="image" @afterRead="afterRead(4,$event)"
						@delete="(event, type) => deletePic(event, 4)" multiple :maxCount="4" width="210rpx"
						height="210rpx" :fileList="otherQualifications" :sizeType="['compressed']"></u-upload>
				</u-form-item>
				<view class="uni-btn-v">
					<view class="">
						<u-button @click="submit" type="primary" :loading="isLoading" loadingText="提交中..."
							text="提交审核"></u-button>
					</view>
					<view class="">
						<u-button @click="reset" text="重置表单"></u-button>
					</view>



				</view>
			</u--form>
		</view>
		<u-datetime-picker :show="timeShow" @cancel="timeShow=false" @confirm='timeConfirm' v-model="time"
			mode="time"></u-datetime-picker>
	</view>

</template>

<script>
	// import CitySelect from "@/components/CitySelect";
	import { resolveAddress } from "@/utils/resolveAddress"
	import {
		getCity,
		MerchantStore
	} from "@/api/user";
	import {
		VUE_APP_API_URL
	} from "@/config";
	import cookie from "@/utils/store/cookie";
	import {
		yxStoreMerchantCategory,
		getStores
	} from "@/api/business";
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				isLoading: false,
				timeShow: false,
				time: '',
				showCateId: false,
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请填写店铺名称',
						trigger: ['blur', 'change']
					},
					'cateId': {
						type: 'string',
						required: true,
						message: '请选择经营类型',
						trigger: ['blur', 'change']
					},
					'province': {
						type: 'string',
						required: true,
						message: '请选择所在地区',
						trigger: ['blur', 'change']
					},
					'phone': {
						type: 'string',
						required: true,
						message: '请选择联系方式',
						trigger: ['blur', 'change']
					},
					'detailedAddress': {
						type: 'string',
						required: true,
						message: '请输入详细地区',
						trigger: ['blur', 'change']
					},
					'_dayTime': {
						type: 'string',
						required: true,
						message: '请设置营业时间',
						trigger: ['blur', 'change']
					},
					// 'dayTime_end': [{
					// 		type: 'string',
					// 		required: true,
					// 		message: '请选择营业结束时间',
					// 		trigger: ['blur', 'change']
					// 	},
					// 	{
					// 		validator: this.dayEndTime,
					// 		// 触发器可以同时用blur和change
					// 		trigger: ['change', 'blur'],
					// 	}
					// ],
					'validTime_start': {
						type: 'string',
						required: true,
						message: '请选择核销开始时间',
						trigger: ['blur', 'change']
					},
					'validTime_end': [{
							type: 'string',
							required: true,
							message: '请选择核销结束时间',
							trigger: ['blur', 'change']
						},
						{
							validator: this.validEndTime,
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'businessLicense': {
						type: 'string',
						required: true,
						message: '请上传营业执照',
						trigger: ['blur', 'change']
					},
					'image': {
						type: 'string',
						required: true,
						message: '请上传门店logo',
						trigger: ['blur', 'change']
					},
					'carouselMap': {
						type: 'string',
						required: true,
						message: '请上传商家轮播图',
						trigger: ['blur', 'change']
					},

				},
				range: [{
					"value": 1,
					"text": "显示"
				}, {
					"value": 2,
					"text": "不显示"
				}],
				form: {
					id: '',
					uid: '',
					name: '',
					cateId: '',
					isShow: 1,
					detailedAddress: '',
					introduction: '',
					phone: '',
					latitude: '',
					dayTime: '', // 营业时间
					// dayTime_start: '',
					// dayTime_end: '',
					validTime_start: '',
					validTime_end: '',
					longitude: '',
					validTime: '',
					businessLicense: [],
					carouselMap: [],
					image: [],
					province: '',

					city: '',
					district: '',
					_dayTime: ''
				},
				businessLicense: [], //营业执照
				image: [], //门店logo
				carouselMap: [], //轮播图
				otherQualifications: [], //其他资质
				cateName: '选择您的门面的类型',
				keys: ``,
				type:'',
				cateList: []
				// 选择省市区
				// addressText: "",
				// district: []
			};
		},
		components: {
			// CitySelect
		},
		computed: mapGetters(["userInfo"]),
		mounted() {
			this.type=this.$yroute.query.type
			if (this.userInfo.roleLevel == 2 && this.userInfo.merchantType == 1) {
				uni.setNavigationBarTitle({title:'开通门店' })
			}else{
				uni.setNavigationBarTitle({title:'修改门店' })
			}
			// this.getCityList();


			// if (this.$yroute.query.time) {
			// 	this.getInfo()
			// }
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form.setRules(this.rules)
			this.getCategory()
		},
		onShow() {
			// if (Object.keys(cookie.get("locaInfo")).length) {
			// 	const locaInfo = cookie.get("locaInfo")
			// 	this.form.detailedAddress = locaInfo.address
			// 	this.form.latitude = locaInfo.latitude
			// 	this.form.longitude = locaInfo.longitude
			// 	this.form.province = locaInfo.district
			// 	this.form.city = locaInfo.city
			// 	this.form.district = locaInfo.town
			// }
		},
		methods: {
			cacheAuthStore() {
				cookie.set("cacheAuthStore", {
					form: this.form,
					image: this.image,
					businessLicense: this.businessLicense,
					carouselMap: this.carouselMap,
					otherQualifications: this.otherQualifications,
					cateName: this.cateName
					// addressText: this.addressText
				})
			},
			goTimePeriod(url) {
				this.cacheAuthStore()
				this.$yrouter.push({
					path: url,
				});
			},
			validEndTime(rule, value, callback) {
				if (!value) {
					callback(new Error("请选择核销结束时间"));
				} else {
					if (!this.form.validTime_start) {
						callback(new Error("请选择核销开始时间！"))
					} else if (Date.parse("2018/10/11 " + this.form.validTime_start) >= Date.parse("2018/10/11 " +
							value)) {
						callback(new Error("核销结束时间必须大于核销开始时间"))
					} else {
						callback();
					}
				}
			},
			// dayEndTime(rule, value, callback) {
			// 	if (!value) {
			// 		callback(new Error("请选择营业结束时间"));
			// 	} else {
			// 		if (!this.form.dayTime_start) {
			// 			callback(new Error("请选择营业开始时间！"))
			// 		} else if (Date.parse("2018/10/11 " + this.form.dayTime_start) >= Date.parse("2018/10/11 " + value)) {
			// 			callback(new Error("营业结束时间必须大于营业开始时间"))
			// 		} else {
			// 			callback();
			// 		}
			// 	}
			// },

			// syncDayTime() {
			// 	this.form.validTime_start = this.form.dayTime_start
			// 	this.form.validTime_end = this.form.dayTime_end
			// },
			// validEndTime(rule, value, callback) {
			// 	if (!value) {
			// 		callback(new Error("请选择核销结束时间"));
			// 	} else {
			// 		if (!this.form.validTime_start) {
			// 			callback(new Error("请选择核销开始时间！"))
			// 		} else if (Date.parse("2018/10/11 " + this.form.validTime_start) >= Date.parse("2018/10/11 " +
			// 				value)) {
			// 			callback(new Error("核销结束时间必须大于核销开始时间"))
			// 		} else {
			// 			callback();
			// 		}
			// 	}
			// },
			// dayEndTime(rule, value, callback) {
			// 	if (!value) {
			// 		callback(new Error("请选择营业结束时间"));
			// 	} else {
			// 		if (!this.form.dayTime_start) {
			// 			callback(new Error("请选择营业开始时间！"))
			// 		} else if (Date.parse("2018/10/11 " + this.form.dayTime_start) >= Date.parse("2018/10/11 " + value)) {
			// 			callback(new Error("营业结束时间必须大于营业开始时间"))
			// 		} else {
			// 			callback();
			// 		}
			// 	}
			// },
			SelectTime(key) {
				this.keys = key
				this.timeShow = true

			},
			timeConfirm(e) {
				this.form[this.keys] = e.value
				this.timeShow = false
				this.cacheAuthStore()
			},


			reset() {

				this.form = this.$options.data().form;
				this.image = []
				this.carouselMap = []
				this.businessLicense = []
				this.otherQualifications = []
				this.cateName = '请选择经营类型'
				// this.addressText = "请选择"
				this.cacheAuthStore()


			},
			submit() {
				let that = this

				this.form.image = this.imageArrSalvage(this.image)
				this.form.carouselMap = this.imageArrSalvage(this.carouselMap)
				this.form.businessLicense = this.imageArrSalvage(this.businessLicense)

				// let address = this.addressText.split('-')
				// this.form.province = address[0]
				// this.form.city = address[1]
				// this.form.district = address[2]
				
				this.form.otherQualifications = this.imageArrSalvage(this.otherQualifications)


				// this.form.dayTime = this.form.dayTime_start + '-' + this.form.dayTime_end
				this.form.validTime = this.form.validTime_start + '-' + this.form.validTime_end

				this.$refs.form.validate().then(res => {
					this.isLoading = true
					// return
					// delete this.form.dayTime_start
					// delete this.form.dayTime_end
					delete this.form.validTime_start
					delete this.form.validTime_end
					delete this.form._dayTime
			
					
					MerchantStore(this.form).then(res => {
						this.isLoading = false
						uni.showToast({
							title: '资料已提交，请耐心等待审核结果~',
							icon: "none"
						});

						setTimeout(() => {
							cookie.remove('cacheAuthStore')
							that.$yrouter.reLaunch({
								path: "/pages/launch/index",
								query: {
									type: 'User'
								}
							});
						}, 1500);
					}).catch(err => {
					    this.form._dayTime = `已设置`
						this.form.validTime_start = this.form.validTime.split('-')[0]
						this.form.validTime_end = this.form.validTime.split('-')[1]
						this.isLoading = false
					})


				}).catch(errors => {
					uni.$u.toast('请完善必填项')
				})
			},
			getInfo() {
				uni.showLoading({
					title: "加载中",
				});
				getStores().then(res => {

					this.form = {
						id: res.data.id,
						uid: res.data.uid,
						name: res.data.name,
						cateId: res.data.cateId,
						address: res.data.address,
						isShow: res.data.isShow,
						detailedAddress: res.data.detailedAddress,
						introduction: res.data.introduction,
						phone: res.data.phone,
						latitude: res.data.latitude,
						longitude: res.data.longitude,
						dayTime: res.data.dayTime,
						validTime: res.data.validTime,
						businessLicense: res.data.businessLicense,
						carouselMap: res.data.carouselMap,
						image: res.data.image,
						province: res.data.province,
						city: res.data.city,
						remark: res.data.remark,
						district: res.data.district,

						validTime_start: res.data.validTime.split('-')[0],
						validTime_end: res.data.validTime.split('-')[1],
					}
					
					if (this.form.dayTime) this.form._dayTime = `已设置`

					this.cateName = this.cateList[0].find(item => item.id == this.form.cateId).cateName
					// this.addressText = res.data.province + '-' + res.data.city + '-' + res.data.district
					// this.form.province = res.data.province
					// this.form.city = res.data.city
					// this.form.district = res.data.district

					this.businessLicense = this.assemblyArr(res.data.businessLicense)
					this.image = this.assemblyArr(res.data.image)
					this.carouselMap = this.assemblyArr(res.data.carouselMap)
					this.otherQualifications = this.assemblyArr(res.data.otherQualifications)
					uni.hideLoading();
				})
			},
			//字符串转数组
			assemblyArr(data) {
				if (data == '' || data == null) return []
				let arr
				if (data.constructor === Array) {
					arr = data
					console.log("data", arr)
				} else {
					arr = data.split(',')
				}

				for (var i = 0; i < arr.length; i++) {
					arr[i] = {
						url: arr[i],
					}
				}
				console.log(arr)
				return arr
			},
			toLoca() {
				const self = this
				uni.chooseLocation({
					latitude: self.form.id ? self.form.latitude : '',
					longitude: self.form.id ? self.form.longitude : '',
					keyword: '',
					success: function(res) {
						resolveAddress({
							latitude: res.latitude,
							longitude: res.longitude
						}).then(data => {
							self.form.detailedAddress = data.address
							self.form.latitude = data.location.lat
							self.form.longitude = data.location.lng
							self.form.province = data.address_component.province
							self.form.city = data.address_component.city
							self.form.district = data.address_reference.town.title
						})
					}
				})
			},
			//cate类型
			getCategory() {
				yxStoreMerchantCategory().then(res => {
					this.cateList = [res.data.content]
					if (this.$yroute.query.type == 1) {
						this.getInfo()
					} else {
						if (cookie.get("cacheAuthStore")) {
							this.form = cookie.get("cacheAuthStore").form
							this.image = cookie.get("cacheAuthStore").image
							this.businessLicense = cookie.get("cacheAuthStore").businessLicense
							this.carouselMap = cookie.get("cacheAuthStore").carouselMap
							this.otherQualifications = cookie.get("cacheAuthStore").otherQualifications
							this.cateName = cookie.get("cacheAuthStore").cateName
							// this.addressText = cookie.get("cacheAuthStore").addressText
							if (this.form.dayTime) this.form._dayTime = `已设置`
						}
					}
				});
			},
			// 获取省市区
			// getCityList: function() {
			// 	let that = this;
			// 	getCity()
			// 		.then(res => {
			// 			that.district = res.data;
			// 			that.ready = true;
			// 		})
			// 		.catch(err => {
			// 			uni.showToast({
			// 				title: err.msg,
			// 				icon: "none",
			// 				duration: 2000,
			// 			});
			// 		});
			// },

			deletePic({
				index
			}, type) {
				if (type == 1) {
					this.businessLicense.splice(index, 1)
				} else if (type == 2) {
					this.image.splice(index, 1)
				} else if (type == 3) {
					this.carouselMap.splice(index, 1)
				} else {
					this.otherQualifications.splice(index, 1)
				}
				this.cacheAuthStore()
			},

			customUpdate(filePath, arr) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${VUE_APP_API_URL}/api/qiNiuContent`,
						filePath: filePath,
						name: 'file',
						formData: {
							bucketName: 'bucket2',
							storeFileName: 'file',
							saveSql: '1'
						},
						header: {
							'token': cookie.get('login_status'),
							// 'token': 'a82472c6-96c9-46b0-a018-783dea7864b5',
							'content-type': 'multipart/form-data' // 默认值
						},
						success: uploadFileRes => {
							if (uploadFileRes.statusCode === 200) {
								var dataResult = JSON.parse(uploadFileRes.data).data;
								resolve(dataResult)
							} else {
								arr.splice(arr.length - 1, 1)
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							}
						},
						fail() {
							arr.splice(arr.length - 1, 1)
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					})
				})
			},
			// 新增图片
			async afterRead(status, event) {
				let arr
				if (status == 1) {
					arr = this.businessLicense
				} else if (status == 2) {
					arr = this.image
				} else if (status == 3) {
					arr = this.carouselMap
				} else {
					arr = this.otherQualifications
				}

				let lists = [].concat(event.file)

				// 记录图片数组起点索引
				let fileListLen = arr.length

				lists.map((item) => {
					arr.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.customUpdate(lists[i].url, arr)
					let item = arr[fileListLen]
					arr.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result[0],
						filePath: result[0]
					}))
					fileListLen++
					this.cacheAuthStore()
				}

			},
			bindPickerChange(e) {
				this.$set(this.form, 'cateId', e.value[0].id + '')
				this.cateName = e.value[0].cateName
				this.showCateId = false
				this.cacheAuthStore()
			},

			imageArrSalvage(arr) {
				if (arr.length <= 0) return ''
				let Array = []
				for (var i = 0; i < arr.length; i++) {
					Array.push(arr[i].url)
				}
				return Array.join(',')
			}
			// result(values) {
			// 	console.log(this);
			// 	console.log(values);
			// 	this.addressText = `${values.province.name}-${values.city.name}-${values.district.name}`;
			// 	this.cacheAuthStore()
			// }
		},
	};
</script>